package com.azusa.xbjy.controller;

import com.azusa.xbjy.entity.Result;
import com.azusa.xbjy.entity.StatusCode;
import com.azusa.xbjy.entity.User;
import com.azusa.xbjy.service.UserService;
import com.azusa.xbjy.utils.EmailUtil;
import com.azusa.xbjy.utils.IdWorker;
import com.azusa.xbjy.utils.LoginUserUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("common")
@RestController
public class CommonController {

    @Autowired
    private UserService userService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EmailUtil emailUtil;

    @RequestMapping("header")
    public ModelAndView getHeader(){
        return new ModelAndView("common/header");
    }

    @RequestMapping("sidebar")
    public ModelAndView getSidebar(){
        return new ModelAndView("common/side");
    }

    @RequestMapping("home")
    public ModelAndView toHome(){
        return new ModelAndView("home");
    }

    /**
     * 登录用户
     * @param username
     * @param password
     * @param code
     * @param session
     * @return
     */
    @RequestMapping("login")
    public Result doLogin(String username, String password,String code, HttpSession session){
        //获取正确的验证码信息
        String checkCode = (String) session.getAttribute("checkCode");
        if (checkCode!=null && checkCode.equals(code)){
            User loginUser = userService.findByUsernameAndPassword(username, password);
            if (loginUser != null){
                //修改登录时间
                loginUser.setLoginTime(new Date());
                userService.save(loginUser);
                //将登录用户存储到session和redis中
                loginUser.setPassword(null);
                session.setAttribute("userId",loginUser.getId());
                redisTemplate.opsForValue().set("loginUser:" + loginUser.getId(),loginUser,2, TimeUnit.HOURS);
                return new Result(StatusCode.SUCCESS,loginUser);
            }
            return new Result(StatusCode.USER_PASSWORD_ERROR);
        }
        return new Result(StatusCode.NO_CODE);
    }

    /**
     * 注销用户
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public ModelAndView toLogout(HttpSession session){
        //清除session中的user信息
        session.removeAttribute("loginUser");
        redisTemplate.delete("loginUser:"+ LoginUserUtil.getId());
        //跳回首页
        return new ModelAndView("home");
    }

    /**
     * 查看邮箱是否已被注册
     * @param email
     * @return
     */
    @RequestMapping("checkEmail/{email}")
    public Result checkEmail(@PathVariable("email") String email){
        User user = userService.findByEmail(email);
        if (user != null){
            //用户已被注册
            return new Result(StatusCode.ERROR,"该邮箱已被注册，请重新输入");
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 查看用户名是否已被注册
     * @param username
     * @return
     */
    @RequestMapping("checkUserName/{username}")
    public Result checkUserName(@PathVariable("username") String username){
        User user = userService.findByUsername(username);
        if (user != null){
            //用户已被注册
            return new Result(StatusCode.ERROR,"该用户名已被注册，请重新输入");
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody User user){
        if (StringUtils.isEmpty(user.getEmail())){
            return new Result(StatusCode.ERROR,"邮箱为空，请重新输入");
        }
        if (StringUtils.isEmpty(user.getUsername())){
            return new Result(StatusCode.ERROR,"用户名为空，请重新输入");
        }
        if (StringUtils.isEmpty(user.getPassword())){
            return new Result(StatusCode.ERROR,"密码为空，请重新输入");
        }
        //...一系列检验
        //用户随机id
        user.setId((int) idWorker.nextId());
        //注册时间
        user.setRegisterTime(new Date());
        user.setRealName(user.getUsername());
        //头像
        user.setPic("http://192.168.31.240:8080/xbjy/upload/0c875f94-02fb-4b7e-9302-120f4ce1de20-123.jpg");
        userService.save(user);
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 发送验证码到指定邮箱
     * @param email
     * @return
     */
    @PutMapping("sendCode/{email}")
    public Result sendCode(@PathVariable("email") String email){
        String code = (idWorker.nextId() + "").substring(0,6);
        //将验证码放入缓存
        redisTemplate.opsForValue().set("code:" + email,code,10,TimeUnit.MINUTES);
        emailUtil.sendMail(email,"主题：小标验证码",code);
        return new Result(StatusCode.SUCCESS,"发送成功");
    }
}
